package conf

import (
	"encoding/json"
	"fmt"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	io "io/ioutil"
	"sync"
	"log"
)

type LeaderConfig struct {
	ChannelId string	`json:channelId`
	Spec string		`json:spec`
	Limit int		`json:limit`

	SourceConf *DbConfig		`json:sourceConf`
	TargetConf *DbConfig		`json:targetConf`


}

type DbConfig struct {
	Host string	 `json:host`
	Port int	`json:port`
	User string	`json:user`
	Password string	`json:password`
	DbName string	`json:dbName`
	Db	*gorm.DB
}






var fileLocker sync.Mutex

func LoadDbConfig()([]LeaderConfig, bool)  {
	return loadConfig("conf/dbconfig.json")
}

func loadConfig(filename string) ([]LeaderConfig, bool) {

	var deviceList []LeaderConfig


	fileLocker.Lock()
	data, err := io.ReadFile(filename)
	fileLocker.Unlock()

	if err != nil {
		fmt.Println("read json file error")
		return deviceList, false
	}
	dataJson := []byte(data)

	err = json.Unmarshal(dataJson, &deviceList)

	if err != nil {
		fmt.Println("unmarshal json file error")
		return deviceList, false
	}
	return deviceList, true
}

func (lConf *LeaderConfig)GetMasterCon() *gorm.DB {
	return lConf.SourceConf.getCon()
}

func  (lConf *LeaderConfig)GetSlaveCon()*gorm.DB  {
	return lConf.TargetConf.getCon()
}







func (dbConfig *DbConfig)getCon()*gorm.DB  {
	var db = dbConfig.Db

	var Host  = dbConfig.Host
	var Port  = dbConfig.Port
	var User  = dbConfig.User
	var Password  = dbConfig.Password
	var DbName  = dbConfig.DbName

	if db == nil{
		connUrl := "host=%s port=%d user=%s password=%s dbname=%s  sslmode=disable TimeZone=Asia/Shanghai"
		connUrl = fmt.Sprintf(connUrl,Host,Port,User,Password,DbName)
		db = connectionDb(connUrl)
		dbConfig.Db = db
	}

	return db
}

func connectionDb(url string) *gorm.DB  {
	db, err := gorm.Open(postgres.Open(url), &gorm.Config{})
	if err != nil {
		log.Fatal(err)
		panic(err)
	}
	return db
}